package com.partybuilding.domain.entity;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.partybuilding.service.AdminRoleService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author wulala
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private Admintable admintable;

    private List<String> permissions;

    private String  roleId;
    @JSONField(serialize = false)
    @JsonIgnore
    private List<SimpleGrantedAuthority> authorities;
    public LoginUser(Admintable admintable,List<String> permissions,String roleId){
        this.admintable=admintable;
        this.roleId=roleId;
        this.permissions=permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //将权限包装为基本实现类，便于过滤器自动搜寻
        if (authorities != null
        ) {
            return authorities;
        }
        else {

            List<SimpleGrantedAuthority> grantedAuthorities=new ArrayList<>();
            for (String permission:permissions)
            {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
                grantedAuthorities.add(authority);
            }
            this.authorities=grantedAuthorities;
            return grantedAuthorities;
        }
    }

    @Override
    public String getPassword() {
        return admintable.getUser_password();
    }

    @Override
    public String getUsername() {
        return admintable.getUser_name();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
